//
//  OosOptionsImpl.m
//  oos4ios
//
//  Created by Pablo Gonzalez on 3/4/11.
//  Copyright 2011 11870.com. All rights reserved.
//

#import <oos4ios/OosEnum.h>
#import "GDataQuery.h"
#import <oos4ios/Options/OosOptions.h>
#import <oos4ios/Exceptions/MethodNotImplementedException.h>


@implementation OosOptions

@synthesize proxy = mProxy;
@synthesize mapping = mMapping;

+ (OosOptions *) options: (NSDictionary *) mapping
{
	return [OosOptions options: mapping withArray: nil];
}

+ (OosOptions *) options: (NSDictionary *) mapping 
				  withArray: (NSArray *) array
{
	return [[[OosOptions alloc] init: (NSDictionary *) mapping 
							   withArray: array] autorelease];
}

- (OosOptions *) init: (NSDictionary *) aMapping 
			   withArray: (NSArray *) array
{
	self = [super init];
	if (self) {
		self.mapping = aMapping;
		self.proxy = array ? [ObjectProxy proxyWithArray:array] : [ObjectProxy proxy];
	}
	return self;
}

- (id) forwardingTargetForSelector:(SEL)aSelector
{
	return self.proxy;
}

- (NSString *) description
{
	return self.proxy.description;
}

- (void) addObject: (id) object 
		   toQuery: (GDataQuery *) query 
		   withKey: (NSString *) key
{
	NSString * value = nil;
	if ([object isKindOfClass:[NSString class]]) {
		value = (NSString *) object;
	} else if ([object isKindOfClass:[NSArray class]]) {
		value = [(NSArray *) object componentsJoinedByString:@","];
	} else if ([object isKindOfClass:[OosEnum class]]) {
		value = [(OosEnum *)object description];
	}
	if (value) {
		[query addCustomParameterWithName:key value:value];
	}
}

- (void) applyToQuery:(GDataQuery *)query
{
	NSDictionary *keyMapping = [self mapping];
	NSDictionary *data = [[self proxy] internalData];
	NSString *mappedKey;
	for (NSString *key in[data allKeys]) {
		if (keyMapping && (mappedKey = [keyMapping objectForKey:key])) {
			key = mappedKey;
		}
		[query addCustomParameterWithName:key 
									value:[data valueForKey:key]];
	}
}

- (void)dealloc
{
    [mMapping release];
    [mProxy release];
    [super dealloc];
}

@end

